
var test = !2;
var myDiagram;
var Temp = function(name){
    var res = {};
    res.default = {
        bg:"rgba(66, 87, 109,0)",
        link:"#999",
        fontOccupy:"#7ab713",
        fontOccupyRed:"red",
        fontParallelGateway:"#f49731",
        fontExclusiveGateway:"#ee5330"
    }
    return res[Temp.from][name];
}
Temp.from = "default";

var groupTemp = function(name,type){
    var res = {};
    res["裁剪组1"] = {
        bkTop:"#673bb7",
        border:"#000"
    }
    res["裁剪组2"] = {
        bkTop:"#673bb7",
        border:"#000"
    }
    res["整烫组2"] = {
        bkTop:"#eb4963",
        border:"#000"
    }
    res["整烫组1"] = {
        bkTop:"#eb4963",
        border:"#000"
    }
    res["手工组"] = {
        bkTop:"#2996f5",
        border:"#000"
    }
    res["西服一组一组（前片里子段）"] = {
        bkTop:"#4ebed3",
        border:"#000"
    }
    res["西服一组一组（袖子段）"] = {
        bkTop:"#607d8b",
        border:"#000"
    }
    res["西服二组二组（前片）"] = {
        bkTop:"#b18750",
        border:"#000"
    }
    res["西服二组二组（后背）"] = {
        bkTop:"#236fa5",
        border:"#000"
    }
    res["西服三组三组"] = {
        bkTop:"#9e9e9e",
        border:"#000"
    }
    res["西服四组四组"] = {
        bkTop:"#9e42b1",
        border:"#000"
    }
    res["西服五组五组"] = {
        bkTop:"#53b050",
        border:"#000"
    }
    res["西服六组六组"] = {
        bkTop:"#2996f5",
        border:"#000"
    }
    res["质检组"] = {
        bkTop:"#cddc39",
        border:"#000"
    }
    res["西服三组十三组"] = {
        bkTop:"#409587",
        border:"#000"
    }
    return res[name]?res[name][type]:'';
}


//  graphobject
;(function(){
    var $$ = go.GraphObject.make;  // for more concise visual tree definitions
    var pathMap;
    var mask = (function(){
        var $mask = $('<div id="mask">');
        var $body = $('body');
        $mask.html('<img src="./assets/img/loading.gif" />');
        return {
            open:function(){
                $body.append($mask);
            },
            close:function(){
                $mask.remove();
            }
        }
    }());

    // diagram - 初始化
    function init() {
        if(myDiagram==void 0){
            var config = {
                allowDrop: true,
                //"LinkDrawn": showLinkLabel,  // this DiagramEvent listener is defined below
                //"LinkRelinked": showLinkLabel,
                "linkingTool.direction": go.LinkingTool.ForwardsOnly,  // only draw "from" towards "to"
                "rotatingTool.snapAngleMultiple": 90,
                "rotatingTool.snapAngleEpsilon": 45,
                "animationManager.isEnabled": false,
                "initialContentAlignment": go.Spot.Center,
                "undoManager.isEnabled": true,
                "allowZoom":true,
                "padding":new go.Margin(100,100),
                "scale":.6,
                //"layout":$$(go.TreeLayout, {
                //    angle: 0,
                //    arrangement: go.TreeLayout.ArrangementVertical,
                //    isRealtime: false,
                //    layerSpacing: 80,
                //    setsPortSpot: false,
                //    setsChildPortSpot: false
                //})
            }
            myDiagram = $$(go.Diagram, "myDiagramDiv",config);
            myDiagram.toolManager.linkingTool.temporaryLink.routing = go.Link.Orthogonal;
            myDiagram.toolManager.relinkingTool.temporaryLink.routing = go.Link.Orthogonal;
            loop();
            //
            pathMap || (pathMap = getPathMap());
        }


        myDiagram.startTransaction();
        // diagram - 面板背景
        document.getElementById("myDiagramDiv").style.backgroundColor = Temp("bg");
        // diagram - 元素组件定义

        // define the group template
        var fieldSubTemplate =
            $$(go.Panel, "TableRow",  // this Panel is a row in the containing Table
                {
                    background: "transparent"
                },
                $$(go.Panel,"Vertical",
                    {alignment: go.Spot.Left},
                    $$(go.Panel,"Vertical",
                        {
                            margin:new go.Margin(0,10),
                            alignment: go.Spot.Left
                        },
                        $$(go.TextBlock,
                            {
                                height:18,
                                name:"occupy_pre",
                                stroke:Temp("fontOccupy"),
                                margin: new go.Margin(10,0,0,0), column: 2, font: "16px sans-serif",alignment: go.Spot.Left
                            },
                            new go.Binding("visible", "",function(node){
                                return ['1','3'].indexOf(node.isWhere)>-1 && !!node.occupy_pre;
                            }),
                            new go.Binding("text", "",function(node){
                                return "●  占压 :  "+ node.occupy_pre;
                            })
                        ),
                        $$(go.TextBlock,
                            {
                                height:20,
                                margin: new go.Margin(20,0,8,0), column: 1, font: "bold 18px sans-serif", alignment: go.Spot.Left,
                                fromLinkable: false, toLinkable: false
                            },
                            new go.Binding("text", "text",function(name){
                                return " - "+name;
                            }),
                            new go.Binding("stroke", "",function(node){
                                var color = 'black';
                                if(node.gateway=="ParallelGateway"){
                                    color = Temp("fontParallelGateway");
                                }else if(node.gateway=="ExclusiveGateway"){
                                    color = Temp("fontExclusiveGateway");
                                }
                                return color;
                            })
                        ),
                        $$(go.TextBlock,
                            {
                                height:18,
                                name:"occupy_next",
                                stroke:Temp("fontOccupy"),
                                margin:0,column: 2, font: "16px sans-serif",alignment: go.Spot.Left
                            },
                            new go.Binding("text", "",function(node){
                                var name = "";
                                if(["ParallelGateway","ExclusiveGateway"].indexOf(node.gateway)>-1){
                                    //
                                }else if(node.occupy_next){
                                    name = "●  占压 :  "+ node.occupy_next
                                }
                                return name;
                            })
                        ),
                        new go.Binding("visible", "text",function(name){
                            return !!name;
                        })
                    )
                ),
                new go.Binding("portId", "key"),
                makePort(new go.Binding("portId","key",function(name){return name+"_L"}), go.Spot.Left, go.Spot.LeftCenter, true, true),
                makePort(new go.Binding("portId","key",function(name){return name+"_R"}), go.Spot.Right, go.Spot.RightCenter, true, true)
            )

        var fieldSubListTemplate =
            $$(go.Panel, "TableColumn",
                {
                    padding:new go.Margin(0,0,15,0),
                    background: "transparent"
                },
                $$(go.Panel,"Auto",
                    {
                        alignment:go.Spot.Top,
                        column:0
                    },
                    $$(go.Shape,
                        {
                            margin:new go.Margin(0,20,20,20),
                            strokeWidth:2,
                            //stroke:"#4dbcd4",
                            fill:null
                        },
                        new go.Binding("stroke", "key",function(o,node){
                            var name = node.part.data.key;
                            return groupTemp(name,"bkTop");
                        })
                    ),
                    $$(go.Panel, "Table",
                        {
                            margin:new go.Margin(20,20),
                            minSize: new go.Size(320, 10),
                            itemTemplate: fieldSubTemplate
                        },
                        new go.Binding("itemArray","child")
                    )
                )
            )

        var fieldTemplate =
            $$(go.Panel, "TableRow",  // this Panel is a row in the containing Table
                {
                    background: "transparent"
                },
                $$(go.Panel,"Vertical",
                    {alignment: go.Spot.Left},
                    $$(go.Panel,"Vertical",
                        {
                            padding: new go.Margin(0,10),
                            margin: new go.Margin(0,10),
                            alignment: go.Spot.Left
                        },
                        $$(go.TextBlock,
                            {
                                height:18,
                                name:"occupy_pre",
                                stroke:Temp("fontOccupy"),
                                margin: new go.Margin(0,0,0,0), column: 2, font: "16px sans-serif",alignment: go.Spot.Left
                            },
                            new go.Binding("visible", "",function(node){
                                return ['1','3'].indexOf(node.isWhere)>-1 && !!node.occupy_pre
                            }),
                            new go.Binding("text", "",function(node){
                                return "●  占压 :  "+ node.occupy_pre;
                            })
                        ),
                        $$(go.TextBlock,
                            {
                                height:20,
                                name:"title",
                                margin: new go.Margin(25,0,8,0), column: 1, font: "bold 18px sans-serif", alignment: go.Spot.Left,
                                fromLinkable: false, toLinkable: false
                            },
                            new go.Binding("stroke", "",function(node){
                                var val = "black";
                                if(node.gateway=="ParallelGateway"){
                                    val = Temp("fontParallelGateway");
                                }else if(node.gateway=="ExclusiveGateway"){
                                    val = Temp("fontExclusiveGateway");
                                }
                                return val;
                            }),
                            new go.Binding("font", "",function(node){
                                var val = "bold 18px sans-serif";
                                if(["ParallelGateway","ExclusiveGateway"].indexOf(node.gateway)>-1){
                                    val = "bold 18px sans-serif";
                                }
                                return val;
                            }),
                            new go.Binding("text", "text",function(name){
                                return " - "+name;
                            })
                        ),
                        $$(go.TextBlock,
                            {
                                height:18,
                                name:"occupy_next",
                                stroke:Temp("fontOccupy"),
                                margin:0, column: 2, font: "16px sans-serif",alignment: go.Spot.Left
                            },
                            new go.Binding("text", "",function(node){
                                var name = "";
                                if(["ParallelGateway","ExclusiveGateway"].indexOf(node.gateway)>-1){
                                    //
                                }else if(node.occupy_next){
                                    name = "●  占压 :  " + node.occupy_next;
                                }
                                return name;
                            })
                        ),
                        new go.Binding("visible", "text",function(name){
                            return !!name;
                        })
                    ),
                    $$(go.Panel, "Table",
                        {
                            background:"white",
                            itemTemplate: fieldSubListTemplate
                        },
                        new go.Binding("itemArray", "child")
                    )
                ),
                new go.Binding("background", "",function(node){
                    var color = 'transparent';
                    if(["ParallelGateway","ExclusiveGateway"].indexOf(node.gateway)>-1){
                        //color = "#f49731"
                    }
                    if(node.isNouse) {
                        color = "#8e8e8e"
                    }
                    return color;
                }),
                new go.Binding("portId", "key"),
                makePort(new go.Binding("portId","key",function(name){return name+"_L"}), go.Spot.Left, go.Spot.LeftCenter, true, true),
                makePort(new go.Binding("portId","key",function(name){return name+"_R"}), go.Spot.Right, go.Spot.RightCenter, true, true)
            );

        myDiagram.nodeTemplateMap.add("Process",
            $$(go.Node, "Auto",
                {
                    movable: true,
                    copyable: false,
                    deletable: false
                },
                new go.Binding("location", "pos", go.Point.parse).makeTwoWay(go.Point.stringify),
                $$(go.Shape, {fill: "white",strokeWidth:3}),
                $$(go.Panel, "Vertical",
                    $$(go.Panel, "Auto",
                        {
                            stretch: go.GraphObject.Horizontal
                        },
                        $$(go.Shape,
                            { stroke: null },
                            new go.Binding("fill","key",function(name){
                                return groupTemp(name,"bkTop");
                            })
                        ),
                        $$(go.TextBlock,
                            {
                                height:24,
                                alignment: go.Spot.Center,
                                margin:15,
                                stroke: "white",
                                textAlign: "center",
                                font: "bold 22px sans-serif"
                            },
                            new go.Binding("text", "text"))),
                    //
                    $$(go.Panel, "Auto",
                        {alignment:go.Spot.Left},
                        $$(go.TextBlock,
                            {
                                height:22,
                                margin:new go.Margin(10,0,10,20),
                                stroke: "#a8a8a8",
                                font: "bold 20px sans-serif"
                            },
                            new go.Binding("text", "",function(node){
                                return node.subtext?"上序 : " + node.subtext:'';
                            }))
                    ),
                    $$(go.Panel, "Table",
                        {
                            name:"Table",
                            padding:new go.Margin(2,2,15,2),
                            minSize: new go.Size(400, 10),
                            defaultStretch: go.GraphObject.Horizontal,
                            itemTemplate: fieldTemplate
                        },
                        new go.Binding("itemArray", "child")
                    ),
                    $$(go.Panel, "Auto",
                        {alignment:go.Spot.Left},
                        $$(go.TextBlock,
                            {
                                height:22,
                                margin:new go.Margin(5,0,15,20),
                                stroke: "#a8a8a8",
                                font: "bold 20px sans-serif"
                            },
                            new go.Binding("text", "",function(node){
                                return node.subtext1?"下序 : " + node.subtext1:'';
                            })
                        ),
                        new go.Binding("visible",'',function(node){
                            return !!node.subtext1;
                        })
                    )
                ),
                makePort("T", go.Spot.Top, go.Spot.AllSides, true, true),
                makePort("B", go.Spot.Bottom, go.Spot.AllSides, true, true)
            ));

        myDiagram.nodeTemplateMap.add("Start",
            $$(go.Node,"Auto",
                {
                    background:"#236fa5",
                    alignment: go.Spot.Center
                },
                $$(go.Shape,"RoundedRectangle",{
                        desiredSize: new go.Size(400, 80),
                        fill:"transparent",
                        strokeWidth:0
                    }
                ),
                $$(go.TextBlock,{
                    margin:10,
                    text:"开始",
                    font: "bold 22px sans-serif",
                    stroke:"white"
                }),
                new go.Binding("location", "pos", go.Point.parse).makeTwoWay(go.Point.stringify),
                makePort("T", go.Spot.Top, go.Spot.AllSides, true, true),
                makePort("L", go.Spot.Left, go.Spot.AllSides, true, true),
                makePort("R", go.Spot.Right, go.Spot.AllSides, true, true),
                makePort("B", go.Spot.Bottom, go.Spot.AllSides, true, true)
            )
        )

        myDiagram.nodeTemplateMap.add("End",
            $$(go.Node,"Auto",
                {
                    background:"#236fa5",
                    alignment: go.Spot.Center
                },
                $$(go.Shape,"RoundedRectangle",{
                        desiredSize: new go.Size(400, 80),
                        fill:"transparent",
                        strokeWidth:0
                    }
                ),
                $$(go.TextBlock,{
                    margin:10,
                    text:"结束",
                    font: "bold 22px sans-serif",
                    stroke:"white"
                }),
                new go.Binding("location", "pos", go.Point.parse).makeTwoWay(go.Point.stringify),
                makePort("T", go.Spot.Top, go.Spot.AllSides, true, true),
                makePort("L", go.Spot.Left, go.Spot.AllSides, true, true),
                makePort("R", go.Spot.Right, go.Spot.AllSides, true, true),
                makePort("B", go.Spot.Bottom, go.Spot.AllSides, true, true)
            )
        )

        myDiagram.linkTemplate =
            $$(go.Link,
                {
                    routing: go.Link.Orthogonal,
                    curve: go.Link.JumpOver,
                    adjusting: go.Link.Stretch,
                    corner: 10,
                    relinkableFrom: true,
                    relinkableTo: true,
                    reshapable: true,
                    resegmentable: true,
                    selectable: true,
                    toShortLength: 0,
                    toEndSegmentLength: 0
                },
                $$(go.Shape, { isPanelMain: true, stroke: "#b5b5b5", strokeWidth: 13 }),
                $$(go.Shape, { isPanelMain: true, stroke: Temp("link"), strokeWidth: 12 }),
                $$(go.Shape, { isPanelMain: true, name: "PIPE", strokeWidth: 8, stroke: "white", strokeDashArray: [10, 10]}),
                new go.Binding("points","points").makeTwoWay(),
                new go.Binding("fromPort","fromPort",function(name){
                    return name;
                }).makeTwoWay(),
                new go.Binding("toPort","toPort",function(name){
                    return name;
                }).makeTwoWay()
            );

        //
        myDiagram.commitTransaction();
    };



    //  diagram - 业务函数
    function makePort(name, align, spot, output, input) {
        var horizontal = align.equals(go.Spot.Top) || align.equals(go.Spot.Bottom);
        var bindPortId = typeof name == "string" ? (new go.Binding("portId","",function(){return name})) : name;
        return $$(go.Shape,
            {
                fill: "transparent",  // changed to a color in the mouseEnter event handler
                strokeWidth: 0,  // no stroke
                width: horizontal ? NaN : 8,  // if not stretching horizontally, just 8 wide
                height: !horizontal ? NaN : 8,  // if not stretching vertically, just 8 tall
                alignment: align,  // align the port on the main Shape
                stretch: (horizontal ? go.GraphObject.Horizontal : go.GraphObject.Vertical),
                //portId: name,  // declare this object to be a "port"
                fromLinkableSelfNode:true,
                fromSpot: spot,  // declare where links may connect at this port
                fromLinkable: output,  // declare whether the user may draw links from here
                toLinkableSelfNode:true,
                toSpot: spot,  // declare where links may connect at this port
                toLinkable: input,  // declare whether the user may draw links to here
                cursor: "pointer",  // show a different cursor to indicate potential link point
                mouseEnter: function(e, port) {  // the PORT argument will be this Shape
                    if (!e.diagram.isReadOnly) port.fill = "blue";
                },
                mouseLeave: function(e, port) {
                    port.fill = "transparent";
                }
            },
            new go.Binding("visible","",function(node){
                return !(/^_/.test(node.key) && node.child);
            }),
            bindPortId
        );
    }

    function definePathPattern(geostr, color, width, cap) {
        if (typeof name !== 'string' || typeof geostr !== 'string') throw new Error("invalid name or geometry string argument: " + name + " " + geostr);
        if (color === undefined) color = "black";
        if (width === undefined) width = 1;
        if (cap === undefined) cap = "square";
        return go.GraphObject.make(go.Shape,
            {
                geometryString: geostr,
                fill: "transparent",
                stroke: color,
                strokeWidth: width,
                strokeCap: cap
            }
        );
    }
    function getPathMap(){
        // Define a bunch of small Shapes that can be used as values for Shape.pathPattern
        var PathPatterns = new go.Map('string', go.Shape);
        PathPatterns.add("Dot", definePathPattern("M0 0 M8 0 L8.1 0", "gray", 4, "round"));
        PathPatterns.add("Herringbone", definePathPattern("M0 0 L2 2 L0 4  M1.1 0.1 L2.1 2.1 L1.1 4.1 M10 0 L12 2 L10 4","white",1,"round"));
        PathPatterns.add("Sawtooth", definePathPattern("M0 3 L4 0 2 6 6 3"));
        //
        return function(name){
            return PathPatterns.getValue(name);
        }
    }

    function loop() {
        var diagram = myDiagram;
        var handerTime = 300;
        var hander;
        var start = function() {
            var oldskips = diagram.skipsUndoManager;
            diagram.startTransaction("start");
            diagram.skipsUndoManager = true;
            if(diagram.scale>0.25){
                for(var key in loop.funs){
                    loop.funs[key]();
                }
            }
            diagram.skipsUndoManager = oldskips;
            diagram.commitTransaction("start");
            clearTimeout(hander);
            hander = setTimeout(start,handerTime);
        }
        //
        hander || start();
    }
    loop.funs = {
        links:function(){
            myDiagram.links.each(function(link) {
                var shape = link.findObject("PIPE");
                if(shape){
                    var off = shape.strokeDashOffset - 4;
                    shape.strokeDashOffset = (off <= 0) ? 20 : off;
                }
            });
        },
        occupy:function(){
            if(!myDiagram.result){return;}
            var arr = myDiagram.result.nodeDataArray;
            var color = Temp("fontOccupy");
            var colorRed = Temp("fontOccupyRed");
            arr.forEach(function(one){
                if(one.group){
                    var node = myDiagram.findPartForKey(one.group).findPort(one.key);
                    if(one.occupy_pre_valid){
                        var el = node.findObject("occupy_pre");
                        el.stroke = color==el.stroke ? colorRed : color;
                    }
                    if(one.occupy_next_valid){
                        var el = node.findObject("occupy_next");
                        el.stroke = color==el.stroke ? colorRed : color;
                    }
                }
            });
        }
    }

    function load() {
        var param = location.search, url = $.baseURI+"/step/newAll" + param;
        if(test){url = './json/team_ajax.json'}
        mask.open();
        $.getJSON(url,{},function(res){//'./json/data.json'  $.baseURI+"/neo4j/all"
            mask.close();
            var data = test==1 ? res : filterData(res);
            myDiagram.model = go.Model.fromJson(data);
        })
    }

    function save(){
        var data = filterParam();//.replace("class","odid\":\"\",\"pos");
        mask.open();
        $.ajax({
            url:$.baseURI+'/step/newPos',
            type:"put",
            contentType:"application/json",
            data:JSON.stringify(data),
            success:function(res){
                mask.close();
                if(res=="success"){
                    alert("OK");
                }
            },
            error:function(){
                mask.close();
                alert("ERROR");
            }
        })
    }

    // filter
    function filterData(result){
        var nodeArr = [];
        var fzRel = result.fzRel;
        var linkRel = result.linkRel;
        Array.prototype.push.apply(nodeArr,result.nodeDataArray);
        myDiagram.result = result;
        // test
        linkRel.forEach(function(v){// occupy-limit:模拟数据50
            if(["103","7","430","26"].indexOf(v.from)>-1){
                v.limit = 50;
            }
        })
        //
        return {
            linkFromPortIdProperty:"fromPort",
            linkToPortIdProperty:"toPort",
            linkDataArray:result.linkDataArray,
            nodeDataArray:dataFilter()
        }
        //
        function dataFilter(){
            var res = [];
            for(var i = nodeArr.length - 1;i > -1;i--){
                var one = nodeArr[i];
                var category = one.category;
                if(one.isGroup){
                    clearNode(one);
                    one.category = "Process";
                    one.text = one.key;
                    one.child = [];
                    res.push(one);
                    nodeArr.splice(i,1);
                }else if(["start","end"].indexOf(one.key)>-1){
                    clearNode(one);
                    one.category = category;
                    res.push(one);
                    nodeArr.splice(i,1);
                }
            }
            //
            res.forEach(function(group){
                if(group.category!="Process"){return;}//|| group.key!="裁剪组2"
                setSubtext(group);
                var first = dataGroupFirst(group);
                if(first){
                    dataGroupItem(group,first);
                    dataGroupNouse(group);
                }
            });
            return res;
        }

        function dataGroupFirst(group,node){
            var res;
            if(group.key=="西服三组十三组"){
                res = {key: "_61", text:"",group:"西服三组十三组",category:""};
            }else{
                nodeArr.every(function(v,i){
                    if(v.group==group.key && ["1","3"].indexOf(v.isWhere)>-1){
                        nodeArr.splice(i,1);
                        res = v;
                        res.prekey = v.key;
                        setOccupy(res);
                        return false;
                    }
                    return true;
                });
            }
            return res;
        }

        function dataGroupItem(group,node){
            if(typeof node == "string"){
                node = getOne(nodeArr,{key:link.to},true);
            }
            if(!node){
                return;
            }else if(node.group != group.key){// 末端
                nodeArr.push(node);
                return;
            }
            clearNode(node);
            group.child.push(node);
            //
            var nowKey = dataFzFilter(group,node) || node.key;// 如果分组:定义分组子节点为起始点
            var link = getOne(linkRel,{from:nowKey});
            if(link){
                setOccupy(node,'',link);
                var next = getOne(nodeArr,{key:link.to},true);
                setOccupy(next,link,'');
                dataGroupItem(group,next);
            }
        }

        function dataGroupNouse(group){
            nodeArr.forEach(function(v){
                if(v.group==group.key){
                    clearNode(v);
                    v.isNouse = 1;
                    group.child.splice(0,0,v);
                }
            });
        }

        function dataFzFilter(group,node){
            var obj = fzRel[node.key];
            if(obj){
                var nextNode = node;
                var allArr = [], indexArr = [];
                //
                if(!/^\_/.test(node.key)){
                    nextNode = {key:"_"+node.key,text:""};
                    clearNode(nextNode);
                    group.child.push(nextNode);
                }
                nextNode.child = [];
                for(var key in obj){
                    var arr = obj[key];
                    var childOne = {key:"_"+key,child:[]};
                    //console.log(key);
                    arr.forEach(function(v,i){
                        var nodeOne = getOne(nodeArr,{key:v},true);
                        if(!nodeOne){
                            //console.warn("node-分支:",v+"未找到");
                            if(v=="216"){
                                nodeOne = $.extend({},getOne(childOne.child,{key:v}));
                                nodeOne.key = "_"+nodeOne.key
                                nodeOne.category = "ParallelGateway";
                            }else{
                                return;
                            }
                        }
                        i == 0 && (nodeOne.isWhere = "1");
                        if(["ParallelGateway","ExclusiveGateway"].indexOf(nodeOne.category)>-1 && arr[i+1]){
                            var nextNode = getOne(nodeArr,{key:arr[i+1]});
                            nextNode.isWhere = "1";
                        }
                        setOccupy(nodeOne);
                        clearNode(nodeOne);
                        childOne.child.push(nodeOne);
                    })
                    nextNode.child.push(childOne);
                    //
                    indexArr.push(arr.pop());
                    Array.prototype.push.apply(allArr,arr);
                }
                //
                return getNextKey(allArr,indexArr);
            }
            return;
        }

        function setSubtext(group){
            var links, prekey, nextkey;
            nodeArr.map(function(v){
                if(v.group == group.key){
                    // pre
                    if(prekey !== "" && ["1",'3'].indexOf(v.isWhere)>-1){
                        links = linkRel.filter(function(vv){return vv.to== v.key;});
                        if(links.length==1){
                            if(prekey==void 0 ){
                                prekey = links[0].from;
                            }else if(prekey!=links[0].from){
                                prekey = "";
                            }
                        }else{
                            prekey = "";
                        }
                    }
                    // next
                    if(nextkey !== "" && ["2",'3'].indexOf(v.isWhere)>-1){
                        links = linkRel.filter(function(vv){return vv.from== v.key;});
                        if(links.length==1){
                            if(nextkey==void 0 ){
                                nextkey = links[0].to;
                            }else if(nextkey!=links[0].to){
                                nextkey = "";
                            }
                        }else{
                            nextkey = "";
                        }
                    }
                }
            });
            //
            prekey && (group.subtext = getOne(result.nodeDataArray,{key:prekey}).text);
            nextkey && (group.subtext1 = getOne(result.nodeDataArray,{key:nextkey}).text);
        }

        function setOccupy(node,prelink,nextlink){
            if(!node){return;}
            if(!node.occupy_pre){
                if(!prelink){
                    var prelinks = linkRel.filter(function(v){return v.to==node.key});
                    prelink = prelinks.length==1?prelinks[0]:'';
                }
                if(prelink){
                    node.occupy_pre = prelink.occupy;
                    node.occupy_pre_valid = prelink.occupy > prelink.limit;
                }
            }
            if(!node.occupy_next){
                if(!nextlink){
                    var nextlinks = linkRel.filter(function(v){return v.from==node.key});
                    nextlink = nextlinks.length==1 ? nextlinks[0] : '';
                }
                if(nextlink){
                    node.occupy_next = nextlink.occupy;
                    node.occupy_next_valid = nextlink.occupy > nextlink.limit;
                }
            }
        }

        function getNextKey(allArr,indexArr){
            var key;
            indexArr.every(function(v){
                return allArr.indexOf(v)>-1 || !(key = v);
            });
            return key;
        }

        function getOne(arr,match,flag){
            var one;
            arr.every(function(v,i){
                var isThis = true;
                for(var key in match){
                    if(match[key]!=v[key]){
                        isThis = false;
                    }
                }
                if(isThis){
                    one = v;
                    flag && (arr.splice(i,1));
                }
                return !isThis;
            });
            return one;
        }

        function clearNode(node){
            if(node.category!="Process"){
                node.gateway = node.category;
            }
            if(!node.pos){node.pos = "";}
            node.category = "";
            node.isNouse = "";
            delete node.isGroup;
        }
    }

    function filterParam(){
        var json = myDiagram.model.toJSON().replace("class","pos");
        var result = JSON.parse(json);
        var nodeArr = result.nodeDataArray;
        var res = [];
        nodeArr.forEach(function(v){
            v.child && v.child.forEach(function(v){
                if(!isNouse(v)){
                    saveChild(v);
                    delete v.child;
                    res.push(v);
                }
            });
            delete v.child;
            res.push(v);
        });

        function saveChild(one){// 工序-child
            if(one.child){// 存在子分支
                one.child.forEach(function(v){
                    v.child.forEach(function(vv){
                        if(!isNouse(vv)) {
                            res.push(vv);
                        }
                    });
                });
            }
        }

        function isNouse(one){
            return /^_/.test(one.key);
        }
        //
        result.nodeDataArray = res;
        return result;
    }

    //
    $.baseURI = "http://172.16.6.235:8080";//172.16.6.235:8080";
    $.API = {
        init:init,
        load:load,
        save:save,
        filter:filterData,
        param:filterParam,
        //
        theme:function(name){
            Temp.from = name;
            init();
        },
        make:function(res){
            if(res){
                res = localStorage.setItem("json");
                myDiagram.model = go.Model.fromJson(res);
            }else{
                res = myDiagram.model.toJSON();
                localStorage.setItem("json",res);
                return res;
            }
        }
    }
}())
